import router from ".";
/**
 * 处理后端返回的路由
 * 把没有的路由都移出
 */
const skipRouterNameArr = ['新增商品','编辑商品','404',"添加管理员","订单详情"] 
export const removeRouter = (data) => {
  const routerNameList = dataUnEmpty(router.getRoutes().map((item) => {
    return item.meta.title;
  }));
  // 获取data里的路由名称
  const dataNameList = dataUnEmpty(getName(data));
  const removeRouterList = dataMerge(routerNameList, dataNameList, 3)
  return new Promise((resolve, reject) => {
    removeRouterList.forEach((item) => {
      if (skipRouterNameArr.includes(item)) {
        return;
      }
      router.removeRoute(item);
    });
    resolve(router.getRoutes());
  });
};
const getName = (data) => {
  const arr = [];

  const stack = [...data];

  while (stack.length > 0) {
    const node = stack.pop();
    if (node.children && node.children.length > 0) {
      stack.push(...node.children);
    } else {
      arr.push(node.meta.title);
    }
  }

  return arr;
};
/**
 * 合并数据，取交集/并集/差集/补集
 * @param {*} data1
 * @param {*} data2
 * @param {*} type 1：并集，2：交集，3：差集，4：补集
 * 并集：合并去重
 * 交集：两个数组都有的值
 * 差集：data1中有，data2中没有的值
 * 补集：两个数组中各自没有的值
 */
const dataMerge = (data1, data2, type = 1) => {
  switch (type) {
    case 1:
      return [...new Set([...data1, ...data2])];
    case 2:
      return data1.filter((item) => data2.includes(item));
    case 3:
      return data1.filter((item) => !data2.includes(item));
    case 4:
      return data1
        .filter((item) => !data2.includes(item))
        .concat(data2.filter((item) => !data1.includes(item)));
  }
};
/**
 * 数组去空
 */
const dataUnEmpty = (data) => {
  return data.filter(
    (item) => item !== "" && item !== null && item !== undefined
  );
};
